//
//  SwipeReturnViewController.m
//  MagTek.iDynamo.ObjC
//
//  Created by agharris73 on 9/4/13.
//  Copyright (c) 2013 Mercury. All rights reserved.
//

#import "SwipeReturnViewController.h"
#import "Home.h"
#import "ePOS-Print.h"
#import "ShowMess.h"
#import <StarIO/SMPort.h>
#import "PrinterFunctions.h"
#import "CommonEnum.h"
#import "DataBaseManager.h"

@interface SwipeReturnViewController ()

@end

@implementation SwipeReturnViewController
{
    //NSMutableString *stringToPrint;
    //UIWebView *webView1;
    NSString *Dbprintertype,*Ipadd,*PayPrinterName,*SearchPrinterStr,*unit,*cardHolderString;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   // NSLog(@"%@",self.resultInf.status);
    self.statusValue.text = self.resultInf.status;
    self.tranTypeValue.text = self.resultInf.tranType;
    self.authCodeValue.text = self.resultInf.authCode;
    self.authAmountValue.text = self.resultInf.authAmount;
    self.amountValue.text = self.resultInf.amount;
    self.taxAmtValue.text = self.resultInf.taxAmt;
    self.acqRefDataValue.text = self.resultInf.acqRefData;
    self.cardTypeValue.text = self.resultInf.cardType;
    self.cvvResultValue.text = self.resultInf.cvvResult;
    self.displayMessageValue.text = self.resultInf.displayMessage;
    self.expDateValue.text = self.resultInf.expDate;
    self.invoiceValue.text = self.resultInf.invoice;
    self.maskedAccountValue.text = self.resultInf.maskedAccount;
    self.refNoValue.text = self.resultInf.refNo;
    self.responseCodeValue.text = self.resultInf.responseCode;
    self.statusMessageValue.text = self.resultInf.statusMessage;
    self.tokenValue.text = self.resultInf.token;
    self.transPostTimeValue.text = self.resultInf.transPostTime;
    
    NSString *querySQL5 = [NSString stringWithFormat: @"SELECT headlines, language,unit,spacing,fontsize,align,Wsize,Hsize,bold,underline,Xposition,printname,print_id,ipaddress,printer_type,searchprinter FROM printer WHERE print_id='%@'",@"printer1"];
    NSMutableArray *printersArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:querySQL5 resultsArray:printersArray];
    NSDictionary *Dict=[printersArray objectAtIndex:0];
   Dbprintertype=[Dict objectForKey:@"printer_type"];
   Ipadd=[Dict objectForKey:@"ipaddress"];
    PayPrinterName=[Dict objectForKey:@"printname"];
    SearchPrinterStr=[Dict objectForKey:@"searchprinter"];
    unit=[Dict objectForKey:@"unit"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];    
}

- (IBAction)startOver:(id)sender {
    NSArray *viewS = [self.navigationController viewControllers];
    NSInteger selectedview;
    // Home *homeview=[[Home alloc]initWithNibName:@"Home" bundle:Nil];
    for (int m=0;m < [viewS count] ; m++)
    {
        if([[self.navigationController.viewControllers objectAtIndex:m] isKindOfClass:[Home class]]){
           selectedview=m;
        }
    }
    [self.navigationController popToViewController:[viewS objectAtIndex:selectedview] animated:YES];
    [self releaseViews];
}

- (IBAction)printmerchnatReceiptClick:(id)sender {
    cardHolderString=@"Card Merchant Copy";
     [self CardbillprintString:self.resultDcit];
}
- (IBAction)printCustomerReceiptClick:(id)sender {
    cardHolderString=@"Card Holder Copy";
    [self CardbillprintString:self.resultDcit];
}
-(void)CardbillprintString:(NSDictionary *)result
{
    NSString *querySQL = [NSString stringWithFormat: @"SELECT merchant_name,merchant_address,merchant_zipcode,server_local,merchant_address2,merchant_phone FROM merchant_info_table"];
    NSMutableArray *merchantDataArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:querySQL resultsArray:merchantDataArray];
    
    NSString *merchnatname,*address1,*address2,*phno,*zipcode;
    if ([merchantDataArray count]>0)
    {
        NSDictionary *Dict=[merchantDataArray objectAtIndex:0];
        merchnatname=[Dict objectForKey:@"merchant_name"];
        address1=[Dict objectForKey:@"merchant_address"];
        address2=[Dict objectForKey:@"merchant_address2"];
        phno=[Dict objectForKey:@"merchant_phone"];
        zipcode=[Dict objectForKey:@"merchant_zipcode"];
        
    }
   NSMutableString *stringToPrint = [[NSMutableString alloc] initWithString:@""];
    
    [stringToPrint appendFormat:@"<html><head><style type=\"text/css\">body {background-color:none;font-family : Verdana;color:#000000;font-size:28px;} table td {font-family : Verdana;color:#000000;font-size:28px; padding:0px 15px;} .tablehead{ font-size:30px;} </style><body style='background-color:none;'><center><table cellspacing=\"10\" width=';95%%' align='center' border=\"0\"><tr><th align=\"center\" colspan=\"2\">AonePOS</th></tr>"];
    
    [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">%@</span></th></tr>",merchnatname];
    [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">%@</span></th></tr>",address1];
    [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">%@</span></th></tr>",address2];
    [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">%@</span></th></tr>",phno];
     [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">%@</span></th></tr>",zipcode];
    
    [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">MerchantID:%@</span></th></tr>",[result objectForKey:@"MerchantID"]];
    
    [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">&nbsp;</span></th></tr><tr><td align=\"left\">Ref No:</td><td align=\"right\">%@<td><tr>",[result objectForKey:@"RefNo"]];
    
    [stringToPrint appendFormat:@"<tr><td align=\"left\">Invoice No:</td><td align=\"right\">%@<td><tr>",[result objectForKey:@"InvoiceNo"]];
    
    [stringToPrint appendFormat:@"<tr><td align=\"left\">Approval Code:</td><td align=\"right\">%@<td><tr>",[result objectForKey:@"AuthCode"]];
    
    [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">&nbsp;</span></th></tr><tr><td align=\"left\"> Card No:</td><td align=\"right\">%@<td><tr>",[result objectForKey:@"AcctNo"]];
    
    
    [stringToPrint appendFormat:@"<tr><td align=\"left\">Exp Date:</td><td align=\"right\">%@<td><tr>",[result objectForKey:@"ExpDate"]];
    
    [stringToPrint appendFormat:@"<tr><td align=\"left\">Card:</td><td align=\"right\"> %@<td><tr>",[result objectForKey:@"CardType"]];
    
    [stringToPrint appendFormat:@"<tr><td align=\"left\">TranID: </td><td align=\"right\">%@<td><tr><br/> ",@""];
    
     [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">Price:%@</span></th></tr>",[result objectForKey:@"Purchase"]];
    
    [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">Signature</span></th></tr>"];
  
    [stringToPrint appendFormat:@"<tr><th align=\"center\" colspan=\"2\"><span class=\"tablehead\">%@</span></th></tr>",cardHolderString];
    
    
    [stringToPrint appendFormat:@"</table></center></body></html>"];
    
    //NSLog(@"print string %@",stringToPrint);
    
       @autoreleasepool {
    UIWebView  *webView1 = [[UIWebView alloc] initWithFrame:CGRectMake(1069, 0, 600, 500)];
    
    [webView1 loadHTMLString:stringToPrint baseURL:nil];
    //webView1.hidden=YES;
    [webView1 setDelegate:self];
    [webView1 sizeToFit];
    //add to main view
    [self.view addSubview:webView1];
    
       }
    stringToPrint=nil,[merchantDataArray removeAllObjects],querySQL=nil;
    
}

-(void)GetPrint:(UIWebView **)webview
{
    
    //UIImageView *myimageView=[[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 600, 600)];
    //[myimageView setImage:[generalDataObject   imageFromWebView:webView1]];
    // [self.view addSubview: myimageView];
    [*webview removeFromSuperview];
    
    
    //[PrinterpopupView removeFromSuperview];
    
    if ([Dbprintertype isEqualToString:@"EPSON"]){
        EposPrint *printer_ = [[EposPrint alloc] init];
        
        int result = [printer_ openPrinter:0 DeviceName:Ipadd Enabled:TRUE Interval:1000];
        if(result != EPOS_OC_SUCCESS)
        {
            [ShowMess showExceptionEpos:result method:@"openPrinter"];
            //[printer release];
            return;
        }
        
        
        //create builder
        EposBuilder *builder = [[EposBuilder alloc] initWithPrinterModel:PayPrinterName Lang:EPOS_OC_MODEL_ANK];
        if(builder == nil)
        {
            return ;
        }
        
        UIImage *printImage=[self imageFromWebView:*webview];
        CGFloat width=printImage.size.width;
        CGFloat height =printImage.size.width;
        
        //result1 = [builder addText:stringToPrint];
        result1 = [builder addImage:printImage X: 0 Y: 0 Width: width Height: height Color: EPOS_OC_PARAM_DEFAULT];
        
        result1 = [builder addCut: EPOS_OC_CUT_FEED];
        if(result1 != EPOS_OC_SUCCESS){
            [ShowMess showExceptionEpos:result1 method:@"addImage"];
            return ;
        }
        
        result1 = [builder addFeedUnit:[[NSString stringWithFormat:@"%@",unit] intValue]];
        if(result1 != EPOS_OC_SUCCESS){
            [ShowMess showExceptionEpos:result1 method:@"addFeedUnit"];
            return ;
            
        }
        
        //send builder data
        unsigned long status = 0;
        unsigned long battery = 0;
        result1 = [printer_ sendData:builder Timeout:10000 Status:&status Battery:&battery];
        [ShowMess showStatus:result1 status:status battery:battery];
        
        
        //remove builder
        [builder clearCommandBuffer];
        printImage=Nil;
        
    }else if ([Dbprintertype isEqualToString:@"STAR"]){
        
        if (blocking == YES)
        {
            return;
        }
        blocking = YES;
        
        
        // CGFloat imagewidth = [self imageFromWebView:webView1].size.width;
        
        //        [PrinterFunctions PrintTextWithPortname:@"TCP:192.168.1.12" portSettings:@"TCP:192.168.1.12" slashedZero:slashedZero underline:underLine invertColor:invertColor emphasized:emphasized upperline:upperline upsideDown:upsideDown heightExpansion:height widthExpansion:width leftMargin:leftMargin alignment:alignment textData:textData textDataSize:[textNSData length]];
        
        NSString *ipaddress=[NSString stringWithFormat:@"%@:%@",SearchPrinterStr,Ipadd];
        // //NSLog(@"ipaddress  %@",ipaddress);
        
        UIImage *printImage=[self imageFromWebView:*webview];
        CGFloat imagewidth=printImage.size.width;
        
        [PrinterFunctions PrintImageWithPortname:ipaddress portSettings:ipaddress imageToPrint:printImage maxWidth:imagewidth compressionEnable:YES withDrawerKick:YES];
        printImage=Nil;
        // free(textData);
        blocking = NO;
        
    }
    
    [*webview loadRequest:nil];
    *webview=nil;
}

-(UIImage *) imageFromWebView:(UIWebView *)view
{
    // tempframe to reset view size after image was created
    CGRect tmpFrame         = view.frame;
    
    // set new Frame
    CGRect aFrame               = view.frame;
    aFrame.size.height  = [view sizeThatFits:[[UIScreen mainScreen] bounds].size].height;
    view.frame              = aFrame;
    
    // do image magic
    UIGraphicsBeginImageContext([view sizeThatFits:[[UIScreen mainScreen] bounds].size]);
    
    CGContextRef resizedContext = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:resizedContext];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    // reset Frame of view to origin
    view.frame = tmpFrame;
    return image;
}

- (IBAction)voidTransactionClick:(id)sender {
    NSMutableDictionary *dictionaryReq = [NSMutableDictionary new];
    
    [dictionaryReq setObject:self.paymentInfo.merchantId forKey:@"MerchantID"];
    [dictionaryReq setObject:self.paymentInfo.tranType forKey:@"TranType"];
    [dictionaryReq setObject:@"VoidSale" forKey:@"TranCode"];
   // [dictionaryReq setObject:self.paymentInfo.invoiceNo forKey:@"InvoiceNo"];
    [dictionaryReq setObject:self.resultInf.refNo forKey:@"RefNo"];
    [dictionaryReq setObject:self.paymentInfo.memo forKey:@"Memo"];
    [dictionaryReq setObject:self.paymentInfo.partialAuth forKey:@"PartialAuth"];
    [dictionaryReq setObject:self.paymentInfo.encryptedFormat forKey:@"EncryptedFormat"];
    [dictionaryReq setObject:self.paymentInfo.accountSource forKey:@"AccountSource"];
    [dictionaryReq setObject:self.paymentInfo.encryptedBlock forKey:@"EncryptedBlock"];
    [dictionaryReq setObject:self.paymentInfo.encryptedKey forKey:@"EncryptedKey"];
    [dictionaryReq setObject:self.paymentInfo.frequency forKey:@"Frequency"];
    [dictionaryReq setObject:self.paymentInfo.recordNo forKey:@"RecordNo"];
    [dictionaryReq setObject:self.paymentInfo.purchase forKey:@"Purchase"];
    [dictionaryReq setObject:self.paymentInfo.name forKey:@"Name"];
    [dictionaryReq setObject:self.paymentInfo.terminalName forKey:@"TerminalName"];
    [dictionaryReq setObject:self.paymentInfo.shiftID forKey:@"ShiftID"];
    [dictionaryReq setObject:self.paymentInfo.operatorID forKey:@"OperatorID"];
    [dictionaryReq setObject:self.resultInf.authCode forKey:@"AuthCode"];
   // [dictionaryReq setObject:self.paymentInfo.address forKey:@"Address"];
   // [dictionaryReq setObject:self.paymentInfo.zip forKey:@"Zip"];
    //    [dictionaryReq setObject:self.paymentInfo.cvv forKey:@"CVV"];
    
    NSString *tranInfoString=[NSString stringWithFormat:@"<TranInfo><AcqRefData>%@</AcqRefData><ProcessData>%@</ProcessData></TranInfo>",self.resultInf.acqRefData,self.resultInf.processData];
    
    MercuryHelper *mgh = [MercuryHelper new];
    mgh.delegate = self;
    [mgh transctionFromDictionary:dictionaryReq andPassword:self.paymentInfo.password url:self.paymentInfo.primaryUrl tranInfo:tranInfoString];
    
}
-(void) transactionDidFailWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"error" message:error.description delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alert show];
}

-(void) transactionDidFinish:(NSDictionary *)result {
    
    if ([[result objectForKey:@"CmdStatus"] isEqualToString:@"Approved"] && [[result objectForKey:@"TextResponse"] isEqualToString:@"REVERSED"]) {
        
        Voidalert = [[UIAlertView alloc] initWithTitle:@"Cancel Transaction" message:@"Are you sure that you want to cancel this transaction ? The amount will be reversed to the customer." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"Cancel",nil];
        [Voidalert show];
       
     
        
    }else if (![[result objectForKey:@"CmdStatus"] isEqualToString:@"Approved"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[result objectForKey:@"CmdStatus"] message:[result objectForKey:@"TextResponse"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
       
        return;
    }
      // NSLog(@"%@",result);
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    if (alertView==Voidalert && buttonIndex==0){
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        appDelegate.resultInf.amount=@"";
        appDelegate.resultInf.authAmount=@"";

        
        NSArray *viewS = [self.navigationController viewControllers];
        NSInteger selectedview;
        // Home *homeview=[[Home alloc]initWithNibName:@"Home" bundle:Nil];
       // NSLog(@"%@",viewS);
        for (int m=0;m < [viewS count] ; m++)
        {
            if([[self.navigationController.viewControllers objectAtIndex:m] isKindOfClass:[Home class]]){
                selectedview=m;
            }
        }
    [self.navigationController popToViewController:[viewS objectAtIndex:selectedview] animated:YES];
        [self releaseViews];
    }
}
-(void)releaseViews
{
   // NSLog(@"release views called");
    [_statusValue removeFromSuperview];
    _statusValue=nil;
    [_tranTypeValue removeFromSuperview];
    _tranTypeValue=nil;
    [_authCodeValue removeFromSuperview];
    _authCodeValue=nil;
    [_authAmountValue removeFromSuperview];
    _authAmountValue=nil;
    [_amountValue removeFromSuperview];
    _amountValue=nil;
    [_taxAmtValue removeFromSuperview];
    _taxAmtValue=nil;
    [_acqRefDataValue removeFromSuperview];
    _acqRefDataValue=nil;
    [_cardTypeValue removeFromSuperview];
    _cardTypeValue=nil;
    [_cvvResultValue removeFromSuperview];
    _cvvResultValue=nil;
    [_displayMessageValue removeFromSuperview];
    _displayMessageValue=nil;
    [_expDateValue removeFromSuperview];
    _expDateValue=nil;
    [_invoiceValue removeFromSuperview];
    _invoiceValue=nil;
    [_maskedAccountValue removeFromSuperview];
    _maskedAccountValue=nil;
    [_refNoValue removeFromSuperview];
    _refNoValue=nil;
    [_responseCodeValue removeFromSuperview];
    _responseCodeValue=nil;
    [_statusMessageValue removeFromSuperview];
    _statusMessageValue=nil;
    [_tokenValue removeFromSuperview];
    _tokenValue=nil;
    [_transPostTimeValue removeFromSuperview];
    _transPostTimeValue=nil;
    
    _paymentInfo=nil;
    _resultInf=nil;
    _resultDcit=nil;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
   
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self GetPrint:&webView];
    [webView removeFromSuperview];
    webView=nil;
}



@end
